package com.azt.data.servlet;

import com.azt.data.utils.CommonUtil;
import com.azt.data.utils.Globals;
import com.azt.data.utils.VerifyCodeUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName AuthImage
 * @Description 图片验证码生成servlet
 * @author Snowler
 * @Date 2016年7月28日 下午3:00:16
 * @version 1.0.0
 */
public class AuthImage extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer w = CommonUtil.safeToInt(request.getParameter("w"), 200);    //宽度
        Integer h = CommonUtil.safeToInt(request.getParameter("h"), 80);     //高度
//        String session_name = request.getParameter("n");    //存到session中的key
//        if(StringUtils.isBlank(session_name)) {
//            session_name = Globals.VALIDATE_IMAGE;
//        }
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        //生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        //存入会话session
        HttpSession session = request.getSession();
        session.setAttribute(Globals.VALIDATE_IMAGE, verifyCode.toLowerCase());
        //生成图片
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

}
